package com.jp.knowledge.view;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;

import com.google.gson.JsonObject;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.JpApplicationWebActivity;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.JsonUtil;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.WebView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/2/24.
 * 全局的 webview
 */

public class JpApplicationWebView extends JpWebView implements JpWebView.JsCallbackListener {

//    protected static String H5_HOST_URL = "http://192.168.33.34:3001";
//    protected static String H5_HOST_URL = "http://m.jianshi580.com/#";
    protected static String H5_HOST_URL = "file:///android_asset/jp580/";

    public static final String WEB_VIEW_CURRENT_PATH = "webViewCurrentPath";
    private static JpApplicationWebView applicationWebView;
    private JpApplicationWebView(Context context) {
        super(context);
        H5_HOST_URL += ("index." + context.getResources().getString(R.string.theme_color_value) + ".html");
        init();
    }
    public static synchronized JpApplicationWebView getInstance(Context context){
        if (applicationWebView == null)
            applicationWebView = new JpApplicationWebView(context.getApplicationContext());
        return applicationWebView;
    }

//    private CommDialog alert;
    private List<JsCallback> jsCallbacks;
    private List<JsCallback> tempJsCallbacks;
    private void init(){
        setClearBeforeLoading(false);
        setShowProgressBar(false);
        setShowLoadingAnimation(false);
        setShowReloadViewOnFail(false);
        setJsCallbackListener(this);
        getWebSettings().setUserAgentString("app_jp;jp580.com");
        jsCallbacks = new ArrayList<>();
        tempJsCallbacks = new ArrayList<>();

//        alert = new CommDialog(getContext());
//        alert.hideCancleBtn();
//        alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

        // 判断 SD 卡上是否有离线包，如果有则读取，没的则读取应用内部的离线包
        String localH5Url;
//        try {
//            localH5Url = getContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/jp580/index.%s.html";
//        } catch (Exception e){
            localH5Url = getContext().getCacheDir() + "/jp580/index.%s.html";
//        }
        if(new File(String.format(localH5Url, context.getResources().getString(R.string.theme_color_value))).exists())
            H5_HOST_URL = "file://" + String.format(localH5Url, context.getResources().getString(R.string.theme_color_value));
        else if(new File(localH5Url.replace(".%s", "")).exists())
            H5_HOST_URL = "file://" + localH5Url.replace(".%s", "");
//        H5_HOST_URL = "http://192.168.33.32:3006";
//        H5_HOST_URL = "file:///android_asset/jp580/index.0694ff.html";
        setTag(H5_HOST_URL);
        loadUrl(H5_HOST_URL);
    }

    /* 自身 JS 回调，返回回调是否向下传递 */
    private boolean handleJsCallback(JsonObject obj){
        try {
            if (obj == null || obj.get("type") == null || obj.get("param") == null)
                return false;
//            if(!"setCurrentPath".equals(obj.get("type").getAsString()))
//                return true;
//            String path = obj.get("param").getAsString();
//            if(path != null && path.equals(webView.getTag())
//                && getTag() != null && getTag() instanceof Context) {
//                Context context = (Context) getTag();
//                context.startActivity(new Intent(context, JpApplicationWebActivity.class)
//                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                        .putExtra(WEB_VIEW_CURRENT_PATH, path));
//                setTag(null);
//                webView.setTag(null);
//            }

            if(!"gotoHtml5".equals(obj.get("type").getAsString()))
                return true;
            if(getTag() != null && getTag() instanceof Context) {
                Context context = (Context) getTag();
                context.startActivity(new Intent(context, JpApplicationWebActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .putExtra(WEB_VIEW_CURRENT_PATH, (String)webView.getTag()));
                setTag(null);
                webView.setTag(null);
            }
        } catch (Exception e){
            return false;
        }
        return false;
    }

    public void openWebActivity(Context context, String path){
        setTag(context);
        webView.setTag(path);
        String param = "{\"type\":\"setCurrentPath\", \"param\":\"" + path + "\"}";
        setCurrentPath(path + "', '" + param);
    }

    public void setCurrentPath(String path){
        loadUrl("javascript:windowNativeBridge.setCurrentPath('" + path + "')");
    }

    public void htmlGoBack(){
        String param = "{\"type\":\"recommendAction\", \"param\":\"goBack\"}";
        loadJavaScript("windowNativeBridge.goBack('', '" + param + "')");
    }

    /* 设置用户信息到 H5 */
    public void setUserDataToH5(UserData userData) {
        JsonObject obj = new JsonObject();
        obj.addProperty("type", "set_user_data");
        String data = (userData == null) ? "{}" : JsonUtil.getInstance().objToJson(userData);
        loadJavaScript("windowNativeBridge.setUserInfoData('" + data + "','" + obj.toString() + "')");
    }

    @Override
    protected void onPageFinished(WebView webView, String url) {
        super.onPageFinished(webView, url);
        if(H5_HOST_URL.equals(getTag())) {
            setTag(null);
            loadJavaScript("windowNativeBridge.setInWebView(2)");
        }
    }

    @Override
    protected boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//        alert.setContent(message);
//        alert.show();
//        result.confirm();
//        return true;
        return super.onJsAlert(view, url, message, result);
    }

    /* 发生 JS 回调 */
    @Override
    public void onJsCallback(JsonObject obj) {
        if(!handleJsCallback(obj))
            return;
        tempJsCallbacks.clear();
        for(JsCallback jsCallback : jsCallbacks)
            if(jsCallback != null)
                tempJsCallbacks.add(jsCallback);
        jsCallbacks.clear();
        jsCallbacks.addAll(tempJsCallbacks);
        for(JsCallback jsCallback : jsCallbacks)
            if(!jsCallback.onJsCallback(obj))
                return;
    }

    /* 添加 JS 回调监听器 */
    public boolean addJsCallback(JsCallback jsCallback){
        if(jsCallbacks.contains(jsCallback))
            return false;
        jsCallbacks.add(0, jsCallback);
        return true;
    }
    public boolean removeJsCallback(JsCallback jsCallback){
        return jsCallbacks.remove(jsCallback);
    }
    public void removeAllJsCallback(){
        jsCallbacks.clear();
    }
    public interface JsCallback{
        boolean onJsCallback(JsonObject obj);   // 返回值代表是否向下传递事件
    }
}
